package com.dayouzi.crawler_data.utils;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 手动维护的自增id，首次加载类从es查询最大id，构造函数传入不同es的索引，获取不同索引的最大id
 */
public class IdGenerator {

    private static RestHighLevelClient client;
    
    private static String esHost;
    
    private static int esPort;
    
    private static String esScheme;
    
    private String index;

    private static AtomicLong id;

    static {
        esHost = PropertiesUtil.getProperties("es.localhost.host");
        esPort = Integer.parseInt(PropertiesUtil.getProperties("es.localhost.port"));
        esScheme = PropertiesUtil.getProperties("es.localhost.scheme");
        
        client = new RestHighLevelClient(RestClient.builder(
                new HttpHost(esHost, esPort, esScheme)
        ));
    }
    
    public IdGenerator(String index) {
        this.index = index;
        // 查询es中id的最大值
        SearchRequest searchRequest = new SearchRequest(index).types("_doc");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.aggregation(AggregationBuilders.max("max_id").field("id"));
        searchRequest.source(sourceBuilder);

        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            Max maxAggregation = response.getAggregations().get("max_id");
            double max_id = maxAggregation.getValue();
            if (Double.isInfinite(max_id)) {
                id = new AtomicLong(0);
            } else {
                id = new AtomicLong((long) max_id);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static long getAutoId() {
        return id.incrementAndGet();
    }


    public static void main(String[] args) {
        
    }

}
